//
//  QBMainView.swift
//  QBCustomImageTag
//
//  Created by 乐启榜 on 16/8/23.
//  Copyright © 2016年 乐启榜. All rights reserved.
//

import UIKit

struct configUserInterface {
    
    var pointViewColor: UIColor = UIColor(white: 0.1, alpha: 0.2)
    var pointShadeColor: UIColor = UIColor(white: 0.1, alpha: 0.2)
    
}

enum overTurnState {// 翻转状态
    case Right      // 文字在点的右边
    case Left       // 文字在点的左边
}

protocol QBTagEditorImageViewDelegate: class {
    
    func didSeletedWithIndex(index: Int)
    func editingWithText(text: String)
}

class QBTagEditorImageView: UIImageView,UIGestureRecognizerDelegate {
    
    var userPoints: [CGPoint] = []
    
    var tagView: QBTagView?
    
    var imageLabelIcon: UIImage?
    
    var imagePreview: UIImageView?
    
    weak var delegate: QBTagEditorImageViewDelegate?
    
    var text: String = "" {
        didSet{
            
            reloadViewWithText(text)
            
            tagView?.textStr = text
            
            if text == "" {
                guard let _tagView = tagView else {return}
                deleteActiveWithView(_tagView)
            }
            
        }
    }

    private let backgroundView: UIView = UIView()
    
    private var blnViewLeftValue: CGFloat = 0.0
    
    private var isOverTurn: Bool = false //翻转状态，默认在文字在点的右边
    
    private var isEditing: Bool = false
    
    private var tagViews: [QBTagView] = []
    
    private var selectedTagView: QBTagView?
    
    private var popMenu: UIMenuController?

    
    init(frame: CGRect, image: UIImage) {
        super.init(frame: frame)
        
        // 1、根据图片的大小重新设置ImageView的frame
        self.frame = setFrame(frame, image: image)
        
        imageLabelIcon = UIImage(named: "textTag")
        
        self.userInteractionEnabled = true
        
        self.contentMode = .ScaleAspectFit
        
        self.image = image
 
        // 2、给ImageView添加点击事件Tap手势
        let imageViewTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageViewTapActive(_: )))
        
        imageViewTap.numberOfTapsRequired = 1
        
        imageViewTap.numberOfTouchesRequired = 1
        
        imageViewTap.delegate = self
        
        self.addGestureRecognizer(imageViewTap)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setFrame(frame: CGRect, image: UIImage) -> CGRect{
        
        // 判断图片的尺寸是不是小于imageView的尺寸
        // 如果图片的尺寸小于imageView的尺寸，将图片的尺寸做为imageView的尺寸
        // 如果图片的尺寸大于imageView的尺寸：
        // 1、 图片宽与高的比例 scale = width / height
        // 2、 对比图片宽与高的大小，判断是宽大于高，还是高大于宽;
        // 3、 如果宽大于高，则需要设置imageView的高，根据图片宽高比scale求imageView得高;
        //     如果高大于宽，则需要设置imageView的宽，根据图片宽高比scale求imageView的宽;
        // 注： imageView.contentMode = .ScaleAspectFit
        var _frame: CGRect = CGRect()
        
        if image.size.width < self.frame.width && image.size.height < self.frame.height {
            
            _frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: image.size.width, height: image.size.height)
            
        } else if image.size.width > self.frame.width && image.size.height > self.frame.height{
            
            // 图片宽与高的比例
            let scaleWH: CGFloat = image.size.width / image.size.height
            
            // 对比图片宽与高的大小， 宽>高
            if image.size.width > image.size.height {
                
                // 根据图片宽高比scale求imageView得高
                let imageViewHeight: CGFloat = self.frame.width / scaleWH
                
                // 设置frame
                _frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: frame.size.width, height: imageViewHeight)
                
            }else if image.size.width < image.size.height {
                
                let imageViewWidth: CGFloat = self.frame.height * scaleWH
                
                _frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: imageViewWidth, height: frame.size.width)
                
            }else if image.size.width == image.size.height {
                
                _frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: frame.size.width, height: frame.size.height)
            }
        }
        
        return _frame
        
    }
    
    @objc private func imageViewTapActive(sender: UITapGestureRecognizer){
        // 3、当用户点击图片时
        
        // 获取用户点击图片的坐标selectedPoint
        let selectedPoint: CGPoint = sender.locationInView(self)
        
        // 将用户点击的坐标保存到数组
        userPoints.append(selectedPoint)
        
        // 添加中心点，让用户知道点击哪里
        addPointView(selectedPoint)
        
        // 弹出填写信息视图
        setChooseView()
    }
    
    private func addPointView(point: CGPoint) {
        
        if let _menuC = popMenu {
            _menuC.setMenuVisible(false, animated: true)
        }
        
        guard let _imageLabelIcon = imageLabelIcon else {return}
        
        let textSize: CGSize = text.qb_stringSizeWithFont(UIFont.systemFontOfSize(11))
            
        tagView = QBTagView(frame: CGRect(x: point.x,
                                          y: point.y - _imageLabelIcon.size.height / 2,
                                          width: textSize.width + 8,
                                          height: _imageLabelIcon.size.height))
        
        selectedTagView = tagView
        
       
        let pan = UIPanGestureRecognizer(target: self, action: #selector(panActive(_: )))
        
        pan.maximumNumberOfTouches = 1
        
        pan.minimumNumberOfTouches = 1
        
        pan.delegate = self
        
        tagView?.addGestureRecognizer(pan)
        
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(tapActive(_: )))
        
        tap.numberOfTapsRequired = 1
        
        tap.numberOfTouchesRequired = 1
        
        tap.delegate = self
        
        tagView?.addGestureRecognizer(tap)

        
        let longTap = UILongPressGestureRecognizer(target: self, action: #selector(longActive(_:)))
        
        longTap.minimumPressDuration = 0.5
        
        longTap.delegate = self
        
        tagView?.addGestureRecognizer(longTap)
        
        self.addSubview(tagView!)
        
        // 添加到数组，做删除功能
        tagViews.append(tagView!)
    }
    /**
     移动标签
     */
    func panActive(sender: UIPanGestureRecognizer){
        
        selectedTagView = sender.view as? QBTagView
        
        let point = sender.locationInView(self)
        
        if sender.state == .Began {
            blnViewLeftValue = point.x - selectedTagView!.frame.origin.x
        }
        
        panTagViewPoint(point)
    }

    
    /**
     viewTag移动
     
     - parameter point: 手指点击的坐标
     */
    func panTagViewPoint(point: CGPoint) {
        
        var rectX: CGFloat = 0.0
        var rectY: CGFloat = 0.0
        
        /**
         *  x轴
         */
        if (point.x - blnViewLeftValue) <= 0 {
            rectX = 0
            
        } else if (point.x + selectedTagView!.frame.width - blnViewLeftValue) >= (frame.origin.x + frame.size.width){
            
            rectX = (frame.origin.x + frame.size.width) - selectedTagView!.frame.width
        
        }else{
            
            rectX = point.x - blnViewLeftValue
        }
        /**
         *  y轴
         */
        if point.y - imageLabelIcon!.size.height / 2 <= 0 {
          
            rectY = 0
        }else if point.y + imageLabelIcon!.size.height / 2 >= frame.height {
           
            rectY = frame.height - imageLabelIcon!.size.height
        }else {
            
            rectY = point.y-imageLabelIcon!.size.height/2
        }
        
        //重新设置frame
        selectedTagView?.frame = CGRect(x: rectX,
                                y: rectY,
                                width: selectedTagView!.frame.width,
                                height: selectedTagView!.frame.height)
    }
    
    /**
     点击
     
     - parameter sender: 点击sender
     */
    
    func tapActive(sender: UITapGestureRecognizer){
        selectedTagView = sender.view as? QBTagView
        
        isEditing = true
        delegate?.editingWithText(selectedTagView!.textStr)
    }

    
    /**
     长按标签，弹出编辑、删除、翻转视图
     */
    func longActive(sender: UILongPressGestureRecognizer){

        selectedTagView = sender.view as? QBTagView
        
        if sender.state == .Began {
            
            self.becomeFirstResponder()
            
            popMenu = UIMenuController.sharedMenuController()
            
            let item1: UIMenuItem = UIMenuItem(title: "编辑",
                                               action: #selector(editingActive))
            
            let item2: UIMenuItem = UIMenuItem(title: "翻转",
                                               action: #selector(isOverTurnActive))
            
            let item3: UIMenuItem = UIMenuItem(title: "删除",
                                               action: #selector(deleteActive))
            
            let items: [UIMenuItem] = [item1,item2,item3]
            
            popMenu?.menuItems = items
            
            popMenu?.arrowDirection = .Down
        
            popMenu?.setTargetRect(selectedTagView!.frame, inView: self)
            
            popMenu?.setMenuVisible(true, animated: true)

        }
    }
    //UIMenuController显示必须实现的方法一
    override func canBecomeFirstResponder() -> Bool {
        return true
    }
    //UIMenuController显示必须实现的方法二
    override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool {
        if action == #selector(isOverTurnActive) || action == #selector(deleteActive) || action == #selector(editingActive) {
            return true
        }
        return false
    }
    
    /**
     编辑
     */
    func editingActive() {
        if let _menuC = popMenu{
            _menuC.setMenuVisible(false, animated: false)
        }
        isEditing = true
        delegate?.editingWithText(selectedTagView!.textStr)
    }
    /**
     翻转
     
     - parameter isOverTurn: 是否翻转
     */
    func isOverTurnActive() {
        
        isOverTurn = !selectedTagView!.isOverTurn // 翻转状态：读取选中视图的翻转状态，取非
        
        var rectX: CGFloat = 0.0
        
        if isOverTurn {                     // 设置blnView的翻转
            
            rectX = selectedTagView!.frame.origin.x - selectedTagView!.frame.width + 8
            
            if selectedTagView!.frame.origin.x - selectedTagView!.frame.width + 8 <= 0 {
                rectX = 0
            }
            
        }else{
            
            rectX = selectedTagView!.frame.origin.x + selectedTagView!.frame.size.width - 8
            
            if rectX > self.frame.width + self.frame.origin.x{
                
                rectX = self.frame.width - selectedTagView!.frame.width
                
            }
        }
        
        selectedTagView?.frame = CGRect(x: rectX, y: selectedTagView!.frame.origin.y, width: selectedTagView!.frame.width, height: selectedTagView!.frame.height)
        
        selectedTagView!.isOverTurn = isOverTurn  // 设置选中视图的翻转状态
        
    }
    /**
     删除
     */
    func deleteActiveWithView(view: QBTagView) {
        
        for (index,_view) in tagViews.enumerate() {
            if view == _view {
                view.removeFromSuperview()
                tagViews.removeAtIndex(index)
            }
        }
 
    }
    // 按删除按钮的删除事件
    func deleteActive() {
        
        guard let _selectedTagView = selectedTagView else {return}
        guard let _menuC = popMenu else {return}
        
        _menuC.setMenuVisible(false, animated: false)
        
        for (index,_view) in tagViews.enumerate() {
            if _selectedTagView == _view {
                _selectedTagView.removeFromSuperview()
                tagViews.removeAtIndex(index)
            }
        }
    }
    
    /**
     重载UI
     
     - parameter text: 编辑后的文字
     */
    func reloadViewWithText(text: String) {
        
        let size: CGSize = text.qb_stringSizeWithFont(UIFont.systemFontOfSize(11))
        let width: CGFloat = size.width + 8 + 15
        
        // 判断是否编辑触发
        // 不是，则为新创建的TagView
        if !isEditing {
            
            var originX: CGFloat = 0.0
            
            guard let _selectedTagView = selectedTagView else {return}
            
            if _selectedTagView.frame.origin.x + width > frame.width{
            
                originX = frame.width - width
                
            }else{
                
                originX = _selectedTagView.frame.origin.x
            }
            
            selectedTagView?.frame = CGRect(x: originX,
                                            y: selectedTagView!.frame.origin.y,
                                            width: width,
                                            height: selectedTagView!.frame.height)
        } else{
            
            if selectedTagView!.isOverTurn {
                
                // 如果选中的TagView的文字在点的左边，即发生翻转
                // 计算OriginX的值： 
                // 计算出改变前的OldOriginX selectedTagView!.frame.origin.x + selectedTagView!.frame.width
                // oldWidth - width 则为现在的OriginX
                
                selectedTagView?.frame = CGRect(x: selectedTagView!.frame.origin.x + selectedTagView!.frame.width - width,
                                                y: selectedTagView!.frame.origin.y,
                                                width: width,
                                                height: selectedTagView!.frame.height)
               
                
            }else{
                
                // 如果选中的TagView的文子在点的右边，即未发生翻转
                // 计算Origin的值为改变前的selectedTagView!.frame.origin.x
                selectedTagView?.frame = CGRect(x: selectedTagView!.frame.origin.x,
                                                y: selectedTagView!.frame.origin.y,
                                                width: width,
                                                height: selectedTagView!.frame.height)
            }
        }
        
    }
}

// MARK:-
// MARK:- 设置弹出视图
extension QBTagEditorImageView {
    
    private func setChooseView() {
        
        let buttonSize: CGFloat = 100
        
        let buttonTitles: [String] = ["商品1","商品2"]
        
        let buttonSpace: CGFloat = (screenBounds().width - CGFloat(buttonTitles.count) * buttonSize) / (CGFloat(buttonTitles.count) + 1)
        
        keyWindow().addSubview(backgroundView)
        
        backgroundView.frame = screenBounds()
        
        backgroundView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.4)
        
        let tapBackgroundView: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapBackgroundViewActive(_: )))
        
        backgroundView.addGestureRecognizer(tapBackgroundView)
        
        
        
        var buttonS: [UIButton] = []
        
        for (index,title) in buttonTitles.enumerate() {
            
            let button = UIButton(type: .Custom)
            
            button.frame = CGRect(x: buttonSpace * CGFloat(index + 1) + buttonSize * CGFloat(index),
                                  y: backgroundView.frame.height / 2 - buttonSize / 2,
                                  width: buttonSize,
                                  height: buttonSize)
            
            button.setTitle(title, forState: .Normal)
            
            button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
            
            button.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.8)
            
            button.layer.cornerRadius = buttonSize / 2
            
            button.clipsToBounds = true
            
            button.addTarget(self, action: #selector(buttonActive(_: )), forControlEvents: .TouchUpInside)
            
            backgroundView.addSubview(button)
            
            buttonS.append(button)
            
        }
        
        UIView.animateWithDuration(0.3, animations: {
            
            for button in buttonS {
                
                button.transform = CGAffineTransformMakeScale(1.2, 1.2)
            }
            
        }) { (finished) in
            
            for button in buttonS {
                
                button.transform = CGAffineTransformIdentity
            }
        }
    }
    
    @objc private func tapBackgroundViewActive(sender: UITapGestureRecognizer) {
        
        // 用户取消编辑时候，去除用户选中的点
        if tagView?.textStr == "" {
            guard let _tagView = tagView else {return}
            deleteActiveWithView(_tagView)
        }
        
        let view: UIView = sender.view!
        
        view.removeFromSuperview()
    }
    
    @objc private func buttonActive(sender: UIButton){
        
        backgroundView.removeFromSuperview()
        
        delegate?.didSeletedWithIndex(0)
        
    }
    
    
    private func keyWindow() -> UIWindow{
        
        return UIApplication.sharedApplication().keyWindow!
    }
    
    private func screenBounds() -> CGRect{
        
        return self.keyWindow().bounds
    }
}


